class dlc {
    constructor() {
        //   this.appid='wx355ed40e6b811a92';
        this.host='https://n.tuku321.com';
        this.look_host = "http://n.tuku321.com/static/mobile/image/"; // 图片路径 
        this.ak = "GkQWRb5vvbjOZKg0v7i3cQF0E4FG4wmS";
        this.trim = (str) => {
            return str.replace(/(^\s*)|(\s*$)/g, "");
        };
        this.formatDate = (now, ff) => {
            let year = now.getFullYear();
            let month = now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1;
            let date = now.getDate() < 10 ? '0' + now.getDate() : now.getDate();
            let hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours();
            let minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes();
            let second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds();
            if (ff == 'Y-m-d') {
                return year + "-" + month + "-" + date;
            } else if (ff == 'Y.m.d') {
                return year + "." + month + "." + date;
            } else if (ff == 'Y-m-d H:i:s') {
                return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
            } else if (ff == 'Y-m-d H:i') {
                return year + "-" + month + "-" + date + " " + hour + ":" + minute;
            } else if (ff == 'm-d') {
                return month + "-" + date;
            } else if (ff == 'Y-m') {
              return year + "-" + month;
          }
        };
    };
    format = (now, ff) => {
        /*日期格式化*/
        let time = now.toString();
        if (time.length == 10) time = time * 1000;
        let d = new Date(time * 1);
        return this.formatDate(d, ff);
    };
    randomn = (n) => {
        let res = ''
        for (; res.length < n; res += Math.random().toString(36).substr(2).toUpperCase()) {}
        return res.substr(0, n)
    };
    newFormData = (arr) => { //手动转FormData格式
        let str = "";
        for (let i in arr) {
            str += '\r\n--XXX' +
                '\r\nContent-Disposition: form-data; name="' + arr[i].name + '"' +
                '\r\n' +
                '\r\n' + arr[i].value
        }
        str += '\r\n--XXX--'
        return str
    };
    isNull = (val) => {
        return val.length == 0 ? true : false;
    };
    formatTime = (second) => {
        /*秒转换成时间*/
        return [parseInt(second / 60 / 60) + '时', parseInt(second / 60 / 60) + '分', second % 60 + '分'].join(",").replace(/,/g, '');
    };

    checkIdCode = (oldValue) => {
        /*判断身份证格式是否正确*/
        let value = this.trim(oldValue);
        let userCardreg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        let taiwanreg = /^[A-Z][0-9]{9}$/; //台湾
        let xianggangreg = /^[A-Z][0-9]{6}\([0-9A]\)$/; //香港
        let aomenreg = /^[157][0-9]{6}\([0-9]\)$/; //澳门
        return (userCardreg.test(value) || taiwanreg.test(value) || xianggangreg.test(value) || aomenreg.test(value));
    };
    //姓名验证
    checkName = (value) => {
        return /^[\u4e00-\u9fa5]{2,4}$/.test(value);
    };
    checkPhone = (value) => { //手机验证
        return /^1\d{10}$/.test(value);
    };
    get_prevPage = (oldPage) => { //获取历史路由对象
        let page = oldPage ? (parseInt(oldPage) + 1) : 2;
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - page];
        if (prevPage == undefined || prevPage == null) return 0;
        return prevPage;
    };
    save = (key, val) => {
        wx.setStorageSync(key, val);
    };
    //滑动渐入渐出
    slideupshow = (that, param, px, opacity) => {
        var animation = wx.createAnimation({
            duration: 800,
            timingFunction: 'ease',
        });
        animation.translateX(px).opacity(opacity).step()
        //将param转换为key
        var json = '{"' + param + '":""}'
        json = JSON.parse(json);
        json[param] = animation.export()
        //设置动画
        that.setData(json)
    }
    //向右滑动渐入渐出
    sliderightshow = (that, param, px, opacity) => {
        var animation = wx.createAnimation({
            duration: 800,
            timingFunction: 'ease',
        });
        animation.translateX(px).opacity(opacity).step()
        //将param转换为key
        var json = '{"' + param + '":""}'
        json = JSON.parse(json);
        json[param] = animation.export()
        //设置动画
        that.setData(json)
    }
    //滑动渐入渐出
    slidetophide = (that, param, px, opacity) => {
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'ease',
        });
        animation.translateY(px).opacity(opacity).step()
        //将param转换为key
        var json = '{"' + param + '":""}'
        json = JSON.parse(json);
        json[param] = animation.export()
        //设置动画
        that.setData(json)
    }
    //验证金钱是否正确
    money = (value) => {
        var str = value;
        var len1 = str.substr(0, 1);
        var len2 = str.substr(1, 1);
        //如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 == 0 && len2 != ".") {
            str = str.substr(1, 1);
        }
        //第一位不能是.
        if (len1 == ".") {
            str = "";
        }
        //限制只能输入一个小数点
        if (str.indexOf(".") != -1) {
            var str_ = str.substr(str.indexOf(".") + 1);
            if (str_.indexOf(".") != -1) {
                str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
            }
        }
        //正则替换，保留数字和小数点
        str = str.replace(/[^\d^\.]+/g, "");
        //如果需要保留小数点后两位，则用下面公式
        str = str.match(/\d+(\.\d{0,2})?/) ? str.match(/\d+(\.\d{0,2})?/)[0] : '';
        return str;
    }
    //倒计时
    formatSeconds = (val, ff) => {
        //相差的总秒数
        var totalSeconds = val;
        //天数
        var days = Math.floor(totalSeconds / (60 * 60 * 24));
        //取模（余数）
        var modulo = totalSeconds % (60 * 60 * 24);
        //小时数
        var hours = Math.floor(modulo / (60 * 60));
        modulo = modulo % (60 * 60);
        //分钟
        var minutes = Math.floor(modulo / 60);
        //秒
        var seconds = modulo % 60;

        function getZero(num) {
            // 单数前面加0
            if (parseInt(num) < 10) {
                num = '0' + num;
            }
            return num;
        }
        //输出到页面
        if (ff == 'cc') {
            // return hours + "小时" + minutes + "分" + seconds+'秒';
            return days + '天' + hours + "小时" + minutes + "分钟";
        } else if (ff == 'h') {
            let hoursd = days * 24 + hours;
            return getZero(hoursd)
        } else if (ff == 's') {
            return getZero(minutes)
        } else if (ff == 'm') {
            return getZero(seconds)
        } else if (ff == 'sm') {
            return getZero(minutes) + ":" + getZero(seconds)
        } else if (ff == 'hsm') {
            return getZero(hours) + ":" + getZero(minutes) + ":" + getZero(seconds)
        } else if (ff == 'text') {
            return days + '天' + getZero(hours) + "时" + getZero(minutes) + "分" + getZero(seconds) + "秒";
        } else {
            return days + '天' + getZero(hours) + ":" + getZero(minutes) + ":" + getZero(seconds);
        }
    };
    //钱保留两位数
    returnFloat = (value) => {
        // var value = Math.round(parseFloat(value) * 100) / 100;
        var value = value * 1;
        var xsd = value.toString().split(".");
        // console.log(xsd)
        if (xsd.length == 1) {
            value = value.toString() + ".00";
            return value;
        }
        if (xsd.length > 1) {
            if (xsd[1].length < 2) {
                value = value.toString() + "0";
            } else if (xsd[1].length > 2) {
                value = xsd[0] + '.' + xsd[1].slice(0, 2)
            }
            return value;
        }
    };
    //获取链接参数
    getQueryString = (name, scan_url) => {
        var reg = new RegExp("[^\?&]?" + encodeURI(name) + "=[^&]+");
        var arr = scan_url.match(reg);
        if (arr != null) {
            return decodeURI(arr[0].substring(arr[0].search("=") + 1));
        }
        return "";
    };
    //读取缓存
    gain = (key) => {
        return wx.getStorageSync(key);
    };
    //删除缓存
    unsave = (key) => {
        wx.removeStorageSync(key)
    };
    //获取链接参数
    getUrlParam = (name, url) => {
        let param = url.substr(url.indexOf('?') + 1);
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = param.match(reg);
        if (r != null) return unescape(r[2]);
        return '';
    };
    goTop = () => {
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0,
                duration: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，可能会影响您的使用。'
            })
        }
    };
    //电话号码中间隐藏
    gettel(number) {
        return number.substring(0, 3) + '****' + number.substring(7);
    }
    /**
     *  判断经纬度是否超出中国境内
     */
    isLocationOutOfChina = (latitude, longitude) => {
        if (longitude < 72.004 || longitude > 137.8347 || latitude < 0.8293 || latitude > 55.8271)
            return true;
        return false;
    }


    /**
     *  将WGS-84(国际标准)转为GCJ-02(火星坐标):
     */
    transformFromWGSToGCJ = (latitude, longitude) => {
        var lat = "";
        var lon = "";
        var ee = 0.00669342162296594323;
        var a = 6378245.0;
        var pi = 3.14159265358979324;

        if (this.isLocationOutOfChina(latitude, longitude)) {
            lat = latitude;
            lon = longitude;
        } else {
            var adjustLat = this.transformLatWithXY(longitude - 105.0, latitude - 35.0);
            var adjustLon = this.transformLonWithXY(longitude - 105.0, latitude - 35.0);
            var radLat = latitude / 180.0 * pi;
            var magic = Math.sin(radLat);
            magic = 1 - ee * magic * magic;
            var sqrtMagic = Math.sqrt(magic);
            adjustLat = (adjustLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
            adjustLon = (adjustLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
            latitude = latitude + adjustLat;
            longitude = longitude + adjustLon;
        }
        return {
            latitude: latitude,
            longitude: longitude
        };

    }

    /**
     *  将GCJ-02(火星坐标)转为百度坐标:
     */
    transformFromGCJToBaidu = (latitude, longitude) => {
        var pi = 3.14159265358979324 * 3000.0 / 180.0;
        var z = Math.sqrt(longitude * longitude + latitude * latitude) + 0.00002 * Math.sin(latitude * pi);
        var theta = Math.atan2(latitude, longitude) + 0.000003 * Math.cos(longitude * pi);
        var a_latitude = (z * Math.sin(theta) + 0.006);
        var a_longitude = (z * Math.cos(theta) + 0.0065);
        return {
            latitude: a_latitude,
            longitude: a_longitude
        };
    }

    /**
     *  将百度坐标转为GCJ-02(火星坐标):
     */
    transformFromBaiduToGCJ = (latitude, longitude) => {
        var xPi = 3.14159265358979323846264338327950288 * 3000.0 / 180.0;
        var x = longitude - 0.0065;
        var y = latitude - 0.006;
        var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * xPi);
        var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * xPi);
        var a_latitude = z * Math.sin(theta);
        var a_longitude = z * Math.cos(theta);
        return {
            latitude: a_latitude,
            longitude: a_longitude
        };
    }

    /**
     *  将GCJ-02(火星坐标)转为WGS-84:
     */
    transformFromGCJToWGS = (latitude, longitude) => {
        var threshold = 0.00001;

        // The boundary
        var minLat = latitude - 0.5;
        var maxLat = latitude + 0.5;
        var minLng = longitude - 0.5;
        var maxLng = longitude + 0.5;

        var delta = 1;
        var maxIteration = 30;

        while (true) {
            var leftBottom = this.transformFromWGSToGCJ(minLat, minLng);
            var rightBottom = this.transformFromWGSToGCJ(minLat, maxLng);
            var leftUp = this.transformFromWGSToGCJ(maxLat, minLng);
            var midPoint = this.transformFromWGSToGCJ((minLat + maxLat) / 2, (minLng + maxLng) / 2);
            delta = Math.abs(midPoint.latitude - latitude) + Math.abs(midPoint.longitude - longitude);

            if (maxIteration-- <= 0 || delta <= threshold) {
                return {
                    latitude: (minLat + maxLat) / 2,
                    longitude: (minLng + maxLng) / 2
                };
            }

            if (this.isContains({
                    latitude: latitude,
                    longitude: longitude
                }, leftBottom, midPoint)) {
                maxLat = (minLat + maxLat) / 2;
                maxLng = (minLng + maxLng) / 2;
            } else if (this.isContains({
                    latitude: latitude,
                    longitude: longitude
                }, rightBottom, midPoint)) {
                maxLat = (minLat + maxLat) / 2;
                minLng = (minLng + maxLng) / 2;
            } else if (this.isContains({
                    latitude: latitude,
                    longitude: longitude
                }, leftUp, midPoint)) {
                minLat = (minLat + maxLat) / 2;
                maxLng = (minLng + maxLng) / 2;
            } else {
                minLat = (minLat + maxLat) / 2;
                minLng = (minLng + maxLng) / 2;
            }
        }

    }

    isContains = (point, p1, p2) => {
        return (point.latitude >= Math.min(p1.latitude, p2.latitude) && point.latitude <= Math.max(p1.latitude, p2.latitude)) && (point.longitude >= Math.min(p1.longitude, p2.longitude) && point.longitude <= Math.max(p1.longitude, p2.longitude));
    }

    transformLatWithXY = (x, y) => {
        var pi = 3.14159265358979324;
        var lat = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        lat += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
        lat += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
        lat += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
        return lat;
    }

    transformLonWithXY = (x, y) => {
        var pi = 3.14159265358979324;
        var lon = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        lon += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
        lon += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
        lon += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
        return lon;
    }
    transformtxbd = (x, y) => { //腾讯转百度
        var latlng = this.transformFromWGSToGCJ(x, y);
        var latlngs = this.transformFromGCJToBaidu(latlng.latitude, latlng.longitude)
        return {
            lat: latlngs.latitude,
            lng: latlngs.longitude
        }
    }
    transformbdtx = (x, y) => { //百度转腾讯
        var latlng = this.transformFromBaiduToGCJ(x, y);
        var latlngs = this.transformFromGCJToWGS(latlng.latitude, latlng.longitude)
        return {
            lat: latlngs.latitude,
            lng: latlngs.longitude
        }
    }
    timeago = (dateTimeStamp) => {
        var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
        var hour = minute * 60;
        var day = hour * 24;
        var week = day * 7;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime(); //获取当前时间毫秒
        var diffValue = now - dateTimeStamp; //时间差
        if (diffValue < 0) {
            return;
        }
        var minC = diffValue / minute; //计算时间差的分，时，天，周，月
        var hourC = diffValue / hour;
        var dayC = diffValue / day;
        // var weekC = diffValue / week;
        // var monthC = diffValue / month;
        var result = ""
        // if (monthC >= 1 && monthC <= 3) {
        //   result = " " + parseInt(monthC) + "月前"
        // } else if (weekC >= 1 && weekC <= 3) {
        //   result = " " + parseInt(weekC) + "周前"
        // } else
        if (dayC >= 1 && dayC <= 3) {
            result = " " + parseInt(dayC) + "天前"
        } else if (hourC >= 1 && hourC <= 23) {
            result = " " + parseInt(hourC) + "小时前"
        } else if (minC >= 1 && minC <= 59) {
            result = " " + parseInt(minC) + "分钟前"
        } else if (diffValue >= 0 && diffValue <= minute) {
            result = "刚刚"
        } else {
            var datetime = new Date();
            datetime.setTime(dateTimeStamp);
            console.log(datetime)
            var Nyear = datetime.getFullYear();
            var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
            var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            // var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
            // var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
            // var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
            // result = Nyear + "-" + Nmonth + "-" + Ndate + ' ' + Nhour + ':' + Nminute + ':' + Nsecond
            result = Nyear + "-" + Nmonth + "-" + Ndate
        }
        return result;
    }
    look_pic(e, list) {
        let url = e.currentTarget.dataset.url;
        let arr = e.currentTarget.dataset.list ? e.currentTarget.dataset.list : list;
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: arr // 需要预览的图片http链接列表
        })
    }
    brand_card = (val) => {
        let value = val;
        if (value && value.length > 8) {
            return `${value.substring(0, 4)} ${"*".repeat(value.length - 8).replace(/(.{4})/g, `
            $1 `)}${value.length % 4 ? " " : ""}${value.slice(-4)}`;
        }
        return value;
    }
    gettel = (number) => {
        return number.substring(0, 3) + '****' + number.substring(7);
    }

    /*函数节流*/
    throttle(fn, interval) {
        var enterTime = 0; //触发的时间
        var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
        return function () {
            var context = this;
            var backTime = new Date(); //第一次函数return即触发的时间
            if (backTime - enterTime > gapTime) {
                fn.call(context, arguments);
                enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
            }
        };
    }

    /*函数防抖*/
    debounce(fn, interval) {
        var timer;
        var gapTime = interval || 1000; //间隔时间，如果interval不传，则默认1000ms
        return function () {
            clearTimeout(timer);
            var context = this;
            var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
            timer = setTimeout(function () {
                fn.call(context, args);
            }, gapTime);
        };
    }
    delete_empty(value) {
        return value.replace(/\s*/g, "")
    }
}
export {
    dlc
}